package com.ruike.alisurface.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.services.NetWorkListenerService;
import com.ruike.alisurface.ui.dialog.CustomDialog;
import com.ruike.alisurface.ui.mainPage.BindMachineActivity;
import com.ruike.alisurface.ui.mainPage.LoginActivity;
import com.ruike.alisurface.ui.mainPage.ShowQrCodeActivity;
import com.ruike.alisurface.ui.mainPage.VedioAdvActivity;
import com.ruike.alisurface.ui.serialportTest.TestSerialPortActivity;
import com.ruike.alisurface.ui.setting.SettingActivity;
import com.ruike.alisurface.ui.setting.StopSellingActivity;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.DeviceUtils;
import com.ruike.alisurface.utils.Languages.LanguageUtil;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ThreadUtils;
import com.ruike.alisurface.utils.ZXingUtils;
import com.voodoo.lib_frame.base.BaseActivity;
import com.voodoo.lib_frame.manager.FActivityManager;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;
import com.voodoo.lib_utils.imageLoader.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.HashMap;

import static com.ruike.alisurface.utils.ShareKey.BASEUSERID;
import static com.ruike.alisurface.utils.ShareKey.SERVICE_TEL;

/**
 * Author: voodoo
 * CreateDate: 2020-03-25 025 下午 03:01
 * Description: 项目的Activity基类，项目中所有Activity完全继承自该类
 */
public abstract class BaseAty extends BaseActivity implements View.OnClickListener {

    private MyCountDownTimer countDownTimer;
    boolean isReboot = false;
    Bitmap SnBitmap;
    Bitmap UrlBitmap;

    /**
     * 此方法先于 onCreate()方法执行
     *
     * @param newBase
     */
    @Override
    protected void attachBaseContext(Context newBase) {
        //获取我们存储的语言环境 比如 "en","zh",等等
        String language = ShareUtils.getInstance().getString(ShareKey.LANGUAGE, "");

        /**
         * attach对应语言环境下的context
         */
        super.attachBaseContext(LanguageUtil.attachBaseContext(newBase, language));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
//            L.i("注册EventBus", this.getComponentName());
            EventBus.getDefault().register(this);
        }
    }

    public static int signalStrength;
    int mCountLog = 0;//根据次数进行日志记录

    @Override
    protected void onResume() {
        super.onResume();
        /**
         *处理信号的回调及UI更新
         */
        NetWorkListenerService.setPhoneWaftListener(new NetWorkListenerService.PhoneWaftListener() {
            @Override
            public void onStrengthsChanged(String type, int signalStrengths) {
                if ("TYPE_WIFI".equals(type)) {
                    signalStrength = 100 + signalStrengths;
                } else {
                    signalStrength = signalStrengths;
                }
                if (mCountLog++ >= 20) {
                    mCountLog = 0;
                    L.i("mqtt  开启信号检测服务 信号大小==" + type + "==" + signalStrength);
                }
                if (waft_lay != null) {
                    waft_lay.setVisibility(View.VISIBLE);
                }
                if (title_waft_content == null && title_waft_img == null) {
                    return;
                }
                if (signalStrength > 0 && signalStrength <= 10) {
                    title_waft_img.setImageResource(R.drawable.icon_signal_1);
                    title_waft_content.setText("信号微弱");
                } else if (signalStrength > 10 && signalStrength <= 30) {
                    title_waft_img.setImageResource(R.drawable.icon_signal_2);
                    title_waft_content.setText("信号弱");
                } else if (signalStrength > 30 && signalStrength <= 60) {
                    title_waft_img.setImageResource(R.drawable.icon_signal_3);
                    title_waft_content.setText("信号中");
                } else if (signalStrength > 60) {
                    title_waft_img.setImageResource(R.drawable.icon_signal_4);
                    title_waft_content.setText("信号强");
                } else if (signalStrength <= 0) {
                    title_waft_img.setImageResource(R.drawable.icon_signal_0);
                    title_waft_content.setText("无信号");
                }
                if (signalStrength <= 0) {
                    isReboot = true;
                } else {
                    isReboot = false;
                    if (dialog != null && dialog.isShowing()) {
                        dialog.cancel();
                        ThreadUtils.removeCallbacks(RebootUi);
                        L.i("mqtt  有信号了 取消弹窗 及计时线程");
                    }
                }
            }
        });

    }

    CustomDialog dialog;
    int restCount;

    /**
     * 提示无网络开始倒数计时重启
     *
     * @param tip
     */
    public void goRebootTip(String tip) {
        if (dialog != null && dialog.isShowing()) {

        } else {
            dialog = new CustomDialog.Builder(BaseAty.this).setTitle("温馨提示")
                    .setMessage(tip).setTouchOutsideCloseDialog(true).create();
            dialog.show();
            restCount = ShareUtils.getInstance().getInt(ShareKey.IS_OFFLINE_RESTART_APPCOUNT, 10);
            if (restCount <= 0) {
                ShareUtils.getInstance().putBoolean(ShareKey.IS_STOP_SELLING, true); // 停止售卖
                startActivity(StopSellingActivity.class, null);
                return;
            }

            ThreadUtils.postUIDelayed(RebootUi, 60000);
        }
    }

    Runnable RebootUi = new Runnable() {
        @Override
        public void run() {
            if (isReboot) {
                --restCount;
                ShareUtils.getInstance().putInt(ShareKey.IS_OFFLINE_RESTART_APPCOUNT, restCount);
                setNoRestMachine();
            }
        }
    };

    /**
     * 重启机器
     */
    public void setNoRestMachine() {
        //重启板子
        String cmd = "su -c reboot";
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
            L.i("onClick: ===" + process.waitFor());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    ImageView title_waft_img;
    TextView title_waft_content;
    RelativeLayout waft_lay;
    TextView snTv;

    @SuppressLint("ClickableViewAccessibility")
    public void initTitleBar(boolean isRightClickToSetting) {
        L.i("信号 initTitleBar", this.getComponentName());
        RelativeLayout titleBar_root_rlayout = findViewById(R.id.titleBar_root_rlayout);
        ImageView titleBar_qrcode_imgv = findViewById(R.id.titleBar_qrcode_imgv);
//        TextView appVersionTv = findViewById(R.id.titleBar_appVersion_tv);
//        ImageView titleBar_titleIco_imgv = findViewById(R.id.titleBar_titleIco_imgv);
        waft_lay = findViewById(R.id.waft_lay);
        title_waft_img = findViewById(R.id.title_waft_img);
        title_waft_content = findViewById(R.id.title_waft_content);

//        if (Constant.isNoTtitle) {
//        } else {
//            titleBar_titleIco_imgv.setVisibility(View.VISIBLE);
//        }
//        appVersionTv.setText(BuildConfig.VERSION_NAME);
//        snTv = findViewById(R.id.titleBar_sn_tv);
//        snTv.setText(new StringBuffer().append(getString(R.string.afterMarketPhoneStr)).append("：").append(ShareUtils.getInstance().getString(ShareKey.SERVICE_TEL, getString(R.string.noPhoneStr))));

        setDataSNcode(titleBar_qrcode_imgv);

        final int[] mLastTouchX = new int[1];
        final int[] mLastTouchY = new int[1];
        final long[] touchTime = new long[1];
        titleBar_root_rlayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mLastTouchX[0] = (int) event.getX();
                        mLastTouchY[0] = (int) event.getY();
                        touchTime[0] = System.currentTimeMillis();
                        L.i("按下横向坐标：X=" + mLastTouchX[0]);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        // 获取手指当前所在的位置
                        int x = (int) event.getX();
                        int y = (int) event.getY();
                        // 计算距离
                        int dx = x - mLastTouchX[0];
                        L.i("滑动距离：dX=" + dx);
                        if (y > v.getTop() && y < v.getBottom()) {
                            if (dx > 300) {
                                mLastTouchX[0] = x;
                            } else if (dx < -300) {
//                                if (!(BaseAty.this instanceof SettingActivity)) {
//                                    startActivity(SettingActivity.class, null);
//                                }
                                if (!(BaseAty.this instanceof TestSerialPortActivity)) {
//                                    startActivity(TestSerialPortActivity.class, null);
                                }
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (System.currentTimeMillis() - touchTime[0] <= 300) {
                            L.i("点击");
                            return false;
                        }
                        break;
                }
                return true;
            }
        });

        titleBar_qrcode_imgv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Ttys3Utils.getInstance().DoorSetting(0,10,0);
//                L.i("dianji==","测试机主电话");
//                Map<String, Object> coflist = new HashMap<>();
//                coflist.put("sn", DeviceUtils.getDeviceSn());
//                coflist.put("service_tel", "1234567890");
//                String data = GsonUtils.StringMapToJson(coflist);
//                MqttOperation.publishMessage(Constant.Mqtt.SERVICE_TEL, data);
            }
        });
        if (isRightClickToSetting) {
            findViewById(R.id.titleBar_setting_view).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    continuousClick();
                }
            });
        }
    }

    /**
     * 设置二维码
     *
     * @param codeimg
     */
    public void setDataSNcode(ImageView codeimg) {
        HashMap<String, String> map = new HashMap<>();
        map.put("version", "Android");
        map.put("sn", DeviceUtils.getDeviceSn());
        String jsonSN = GsonUtils.MapToJson(map);
        SnBitmap = ZXingUtils.createQRImage((jsonSN), 300, 300, BitmapFactory.decodeResource(getResources(), 0));
        ImageLoader.loadImage(this, SnBitmap, codeimg);
    }

    /**
     * 开始倒计时
     *
     * @param time    倒计时时间，单位：秒
     * @param showTv  展示倒计时的TextView
     * @param jumpAty 倒计时结束时跳转的界面
     */
    public void startCountdownTimer(int time, final TextView showTv, Class jumpAty) {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        countDownTimer = new MyCountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long l) { // 展示倒计时
                if (showTv != null) {
                    int time = (int) (l / 1000) + 1;
                    if (time < 20) {
                        showTv.setTextColor(getResources().getColor(R.color.colorCountdownTimeRed));
                    }
                    showTv.setText(new StringBuffer(String.valueOf(time)).append("s"));
                }
            }

            @Override
            public void onFinish() {

                FActivityManager.getInstance().killOtherActivity();
                String baseUserid = ShareUtils.getInstance().getString(BASEUSERID, "RK_test");
                if (baseUserid.equals("RK_test")) {
                    startActivity(BindMachineActivity.class, null);
                    finish();
                    return;
                }
                if (ShareUtils.getInstance().getBoolean(ShareKey.IS_STOP_SELLING, false)) {
                    startActivity(StopSellingActivity.class, null); // 停止售卖
                } else {
                    if (jumpAty != null) {
                        if (jumpAty.getName().contains("MainActivity")) {
                            BackMainUtils.setActivity(BaseAty.this);
                        } else {
                            // 倒计时结束之后直接跳转指定的界面
                            startActivity(jumpAty, null);
                        }
                    } else {
                        // 跳到广告或者是主界面
                        int advType = ShareUtils.getInstance().getInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_NONE);
                        switch (advType) {
                            // 0和1是广告界面，跳转过去之后广告界面内部有图片或者视频广告的判断
                            case 0:
                            case 1:
                                startActivity(VedioAdvActivity.class, null);
                                break;
                            default: // 2或者是其他值则判定为无广告，判断一下是否停止售卖或者是商品展示类界面
                                startActivity(ShowQrCodeActivity.class, null); // 展示商品列表
//                                if (ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 1) == 1) {
//                                    startActivity(MainActivity.class, null); // 按货道展示商品
//                                } else {
//                                    startActivity(MainTypeActivity.class, null); // 按货商品类型示商品
//                                }
                                break;
                        }
                    }
                }
                finish();
            }
        }.start();
    }


    protected void CountdownTimercancal() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    final static int COUNTS = 5;// 点击次数
    final static long DURATION = 2000;// 规定有效时间
    long[] mHits = new long[COUNTS];

    // 多次连续点击
    protected void continuousClick() {
        // 每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        // 为数组最后一位赋值
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
            mHits = new long[COUNTS]; // 重新初始化数组

            String baseUserid = ShareUtils.getInstance().getString(BASEUSERID, "RK_test");

            if (baseUserid.equals("RK_test") || BuildConfig.DEBUG) {
                startActivity(SettingActivity.class, null);
            } else {
                startActivity(LoginActivity.class, null);
            }
            finish();
        }
    }

    @Override
    public void onNetChange(int netMobile, boolean isConnect) {
        if (!isConnect && ShareUtils.getInstance().getBoolean(ShareKey.IS_OFFLINE_RESTART_APP)) {
//            showErrorTip(getResources().getString(R.string.networkDisconnectAndRestartAppStr));
            if (NetWorkListenerService.mPhoneWaftListener != null) {
                NetWorkListenerService.mPhoneWaftListener.onStrengthsChanged("TYPE_MOBILE", 0);

                goRebootTip("机器无网络了，一分钟会自动重启");
                // 断网重启APP
            }
        } else if (!isConnect) {
            showToast(getResources().getString(R.string.networkDisconnectStr));
            if (NetWorkListenerService.mPhoneWaftListener != null) {
                NetWorkListenerService.mPhoneWaftListener.onStrengthsChanged("TYPE_MOBILE", 0);
            }
        }
    }


    /**
     * EventBus 回调
     *
     * @param event
     */
    public abstract void doEventBusResult(MsgEventBus event);

    // 当一个Message Event提交的时候这个方法会被调用
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusResult(MsgEventBus event) {
        L.i("onMessageEvent： ", event.toString());
        doEventBusResults(event);
        doEventBusResult(event);
    }

    /**
     * EventBus 回调
     *
     * @param event
     */
    public void doEventBusResults(MsgEventBus event) {
        if (snTv != null && event.getType().equals(SERVICE_TEL)) {
            snTv.setText(new StringBuffer().append(getString(R.string.afterMarketPhoneStr)).append("：").
                    append(ShareUtils.getInstance().getString(ShareKey.SERVICE_TEL, getString(R.string.noPhoneStr))));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();


    }

    @Override
    protected void onStop() {
        super.onStop();
        CountdownTimercancal();
        if (EventBus.getDefault().isRegistered(this)) {
//            L.i("EventBus，解除绑定", this.getComponentName());
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (SnBitmap != null) {
            SnBitmap.recycle();
            SnBitmap = null;
        }
        if (UrlBitmap != null) {
            UrlBitmap.recycle();
            UrlBitmap = null;
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        if (dialog != null && dialog.isShowing()) {
            dialog.cancel();
            dialog = null;
        }
    }
}
